import { renderFormItem } from '@/components/WorkFlow/partials/FormPanel/utils/renderFormItem'
import { SchedulerService } from '@/service'
import { Button, Form, message } from 'antd'
import { forwardRef, useImperativeHandle, useRef, useState } from 'react'
import Modal from '~/components/Modal'
import { formConfig } from './helper'
import AssignModal from './partials/AssignModal'

const SchedulerModal = (props, ref) => {
  const { title, playbookAllList, typeList = [] } = props
  const [visible, setVisible] = useState(false)
  const [form] = Form.useForm()
  const AssignModalRef = useRef()
  const onOk = () => {
    form.validateFields().then(value => {
      const { playbook_ids } = value
      const targetPlaybook = playbookAllList.find(
        playbook => playbook.value === playbook_ids
      )
      if (!targetPlaybook) return message.error('剧本不存在，请重新选择！')
      if (targetPlaybook.input.length > 0) {
        new Promise((resolve, reject) => {
          AssignModalRef.current.initModal({
            baseData: value,
            input: targetPlaybook.input,
            resolve,
            reject
          })
        })
          .then(res => {
            setVisible(false)
          })
          .catch(err => {
          })
      } else {
        SchedulerService.create(value)
        // 无调度时赋值变量保存
      }
    })
  }
  const onCancel = () => {
    setVisible(false)
  }
  const handleAfterClose = () => {
    form.resetFields()
  }
  useImperativeHandle(ref, () => ({
    initModal
  }))
  const initModal = value => {
    console.log(value);
    
    form.setFieldsValue(value)
    setVisible(true)
  }
  const footer = [
    <Button key="ok" type="primary" onClick={onOk}>
      提交
    </Button>,
    <Button key="cancel" onClick={onCancel}>
      取消
    </Button>
  ]
  return (
    <>
      <Modal
        visible={visible}
        title={title}
        width={600}
        footer={footer}
        onCancel={onCancel}
        afterClose={handleAfterClose}
      >
        <Form autoComplete="off" form={form} labelCol={{ span: 4 }}>
          {formConfig({ playbookAllList, typeList }).map(config =>
            renderFormItem(config)
          )}
        </Form>
      </Modal>
      <AssignModal ref={AssignModalRef}></AssignModal>
    </>
  )
}
export default forwardRef(SchedulerModal)
